//
//  ChatRommViewController.m
//  RTMLibDemo
//
//  Created by admin on 2022/3/30.
//

#import "ChatRoomViewController.h"
#import "UIView+FrameTool.h"
#import "YMKeyboardView.h"
#import "ChatRoomTableViewCell.h"
#import "ChatRoomMyTableViewCell.h"
#import "YMTextView.h"
#import "RTMManager.h"
#import <Foundation/NSString.h>
//状态栏和导航栏的总高度
#define StatusNav_Height (isIphoneX ? 88 : 64)
//判断是否是iPhoneX
#define isIphoneX (K_Width == 375.f && K_Height == 812.f ? YES : NO)
#define K_Width [UIScreen mainScreen].bounds.size.width
#define K_Height self.view.frame.size.height
@interface ChatRoomViewController ()<YMKeyboardDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,YMRTMChannelDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YMKeyboardView *keyView;
@property (nonatomic, strong) NSMutableArray *dataAry;
@property (nonatomic, strong)  YMRTMChannel *channel;
@property (nonatomic,strong)NSString *userId;
@property (nonatomic,strong)UIButton *moreBtn;


@end

@implementation ChatRoomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"频道";
    
    self.view.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.00];
    [self.view addSubview:self.tableView];
    //给UITableView添加手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
    tapGesture.delegate = self;
    [self.tableView addGestureRecognizer:tapGesture];
    
  
    
    //添加输入框
    self.keyView = [[YMKeyboardView alloc] initWithFrame:CGRectMake(0, K_Height - StatusNav_Height+12, K_Width, 52)];
    //设置代理方法
    self.keyView.delegate = self;
    [self.view addSubview:_keyView];
    
 
   
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.userId = [userDefaults valueForKey:@"userId"];
    self.channel =  [[YMRTMManager client] createChannelById:self.channelId];
    self.channel.delegate = self;
    //加入频道
    [self.channel joinChannelWithCompletion:^(YMRTMJoinChannelStatusCode code) {
//        self.showLabel.text = [NSString stringWithFormat:@"成功加入频道：%@",self.channelTF.text];
        NSLog(@"%@成功加入频道",self.userId);
    }];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.moreBtn];
    self.navigationItem.rightBarButtonItem = right;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.channel leaveChannelWithCompletion:^(YMRTMLeaveChannelStatusCode code) {
            

    }];
}
-(void)leaveChannelAction{
    
    [self.channel leaveChannelWithCompletion:^(YMRTMLeaveChannelStatusCode code) {
        
        [self.navigationController popViewControllerAnimated:YES];
        NSLog(@"id:%@离开了频道",self.userId);
    }];
}
#pragma mark - RTMChannelDelegate
- (void)rtmChannel:(YMRTMChannel *)channel memberLeft:(YMRTMMember *)member {
//    self.showLabel.text = [NSString stringWithFormat:@"%@离开了频道",member.userId];
    NSLog(@"id:%@离开了频道",self.userId);
}

- (void)rtmChannel:(YMRTMChannel *)channel memberJoined:(YMRTMMember *)member {
//    self.showLabel.text = [NSString stringWithFormat:@"%@加入了频道",member.userId];
    NSLog(@"id:%@加入了频道",self.userId);
}

- (void)rtmChannel:(YMRTMChannel *)channel didReceiveMessage:(YMRTMMessage *)message {
//    self.showLabel.text = [NSString stringWithFormat:@"收到来自%@的消息：%@",message.uid,message.data];
    NSLog(@"收到来自%@的消息：%@",message.uid,message.data);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:message.uid forKey:@"uid"];
    [dic setValue:message.tid forKey:@"tid"];
    [dic setValue:message.data forKey:@"data"];
    [self.dataAry addObject:dic];
    [self.tableView reloadData];
    [self scrollToBottom];
}

- (void)rtmChannel:(YMRTMChannel *)channel getMembers:(NSArray<YMRTMMember *> *)members {
//    NSLog(@"channel current members:%@",members);
}
#pragma mark ====== UITableViewDelegate ======
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataAry.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    NSMutableDictionary *dic = [self.dataAry objectAtIndex:indexPath.row];
    if ([self.userId isEqualToString:[dic valueForKey:@"uid"]]) {
        static NSString *identifier = @"cell";
        ChatRoomMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
       
        if (cell == nil) {
            
            cell = [[ChatRoomMyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            
        }
        cell.dic = dic;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else{
        
        static NSString *identifier = @"cellid";
        ChatRoomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
       
        if (cell == nil) {
            
            cell = [[ChatRoomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            
        }
        cell.dic = dic;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableDictionary *dic = [self.dataAry objectAtIndex:indexPath.row];
    if ([self.userId isEqualToString:[dic valueForKey:@"uid"]]) {
        
        ChatRoomMyTableViewCell * cell = (ChatRoomMyTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        CGFloat height = [cell.chatTextLable sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width-130, MAXFLOAT) ].height;
        return height+45;
        
    }else{
        
        ChatRoomTableViewCell * cell = (ChatRoomTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        CGFloat height = [cell.chatTextLable sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width-130, MAXFLOAT) ].height;
        return height+45;
    }

}

#pragma mark ====== DKSKeyboardDelegate ======
//发送的文案
- (void)textViewContentText:(NSString *)textStr {
    
    YMRTMMessage *message = [YMRTMMessage createChannelMessageWithChannelId:self.channelId data:textStr];
    
    [self.channel sendMessage:message completion:^(YMRTMSendChannelMessageStatusCode code) {
//        self.showLabel.text = [NSString stringWithFormat:@"频道消息发送成功：%@",self.messageTF.text];
    }];

}

//keyboard的frame改变
- (void)keyboardChangeFrameWithMinY:(CGFloat)minY {
    [self scrollToBottom];
    // 获取对应cell的rect值（其值针对于UITableView而言）
    if (self.dataAry.count==0) {
        return;
    }
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.dataAry.count - 1 inSection:0];
    CGRect rect = [self.tableView rectForRowAtIndexPath:lastIndex];
    CGFloat lastMaxY = rect.origin.y + rect.size.height;
    //如果最后一个cell的最大Y值大于tableView的高度
    if (lastMaxY <= self.tableView.height) {
        if (lastMaxY >= minY) {
            self.tableView.y = minY - lastMaxY;
        } else {
            self.tableView.y = 0;
        }
    } else {
        self.tableView.y += minY - self.tableView.maxY;
    }
}

- (void)scrollToBottom {
    
    if (self.dataAry.count >= 1) {
        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataAry.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
      
    }
}


#pragma mark ====== 点击UITableView ======
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //收回键盘
    [[NSNotificationCenter defaultCenter] postNotificationName:@"keyboardHide" object:nil];
    //若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

#pragma mark ====== init ======
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, K_Width, K_Height - StatusNav_Height - 52) style:UITableViewStylePlain];
        _tableView.separatorStyle = NO;
        _tableView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.00];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 70;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (NSMutableArray *)dataAry {
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}
- (UIButton *)moreBtn {
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_moreBtn setImage:[UIImage imageNamed:@"Friend_More"] forState:UIControlStateNormal];
        [_moreBtn setTitle:@"离开" forState:UIControlStateNormal];
        [_moreBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _moreBtn.frame = CGRectMake(0, 0, 40, 40);
        [_moreBtn addTarget:self action:@selector(leaveChannelAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}
@end



